/*
 * Copyright 2011 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.orkut.androidexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.orkut.client.api.BatchTransaction;
import com.google.orkut.client.api.UpdateProfileTx;
import com.google.orkut.orkroid.Orkroid;
import com.google.orkut.orkroid.OrkroidTask;

public class SetStatusActivity extends Activity implements OrkroidTask.Listener, View.OnClickListener {
	protected Button submitButton, discardButton;
	protected EditText statusText;
	protected ProgressDialog progressDialog = null;
	
	public void onCreate(Bundle savedInstanceBundle) {
		super.onCreate(savedInstanceBundle);
		setContentView(R.layout.setstatusactivity);
		submitButton = (Button) findViewById(R.id.submitbutton);
		discardButton = (Button) findViewById(R.id.discardbutton);
		statusText = (EditText) findViewById(R.id.statustext);
		
		submitButton.setOnClickListener(this);
		discardButton.setOnClickListener(this);
	}
	
	public void onClick(View target) {
		if (target == discardButton) { finish(); return; }
		else if (target == submitButton) {
			progressDialog = ProgressDialog.show(this, "Updating...", "Updating your status...");
			try {
				BatchTransaction btx = Orkroid.getOA().newBatch();
				UpdateProfileTx tx = Orkroid.getOA().getProfileTF().updateSelfProfile();
				btx.add(tx);
				tx.setStatus(statusText.getText().toString());
				OrkroidTask.execute("", btx, this);
			}
			catch (Exception ex) {
				onOrkroidTaskFinished("", null, ex);
			}
		}
	}

	public void showToast(String errmsg) {
		Toast.makeText(this, errmsg, Toast.LENGTH_LONG).show();
	}

	public void onOrkroidTaskFinished(String tag, BatchTransaction btx,
			Exception exc) {
		if (progressDialog != null) progressDialog.dismiss();
		progressDialog = null;
		
		if (exc != null) showToast("Error: " + exc.getMessage());
		else if (btx == null) showToast("Bug: no batch transaction received");
		else {
			showToast("Status updated!");
			finish();
		}
	}
}
